import json
from collections import OrderedDict

from django.core import serializers
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import *

from apps.ads.models import ContentCategory, Content
from apps.goods.models import GoodsCategory, SKU, GoodsChannel
from utils.goods import get_categories, get_breadcrumb


# class IndexView(View):
#     def get(self, request):
#         """
#         首页的数据分为2部分
#         1部分是 商品分类数据
#         2部分是 广告数据
#         """
#         # # 1.商品分类数据
#         # # categories = get_categories()
#         # # print(categories)
#         # #2.广告数据
#         # contents = {}
#         # content_categories = ContentCategory.objects.all()
#         # for cat in content_categories:
#         #     # print(cat.content_set.filter(status=True).order_by('sequence'))
#         #     contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
#         #     print(contents[cat.key])
#         # # categories = json.dumps(categories)
#         # # contents = json.dumps(contents)
#         # context = {
#         #     'categories': categories,
#         #     # 'contents': contents,
#         # }
#         # 广告数据
#         contents = {}
#         content_categories = ContentCategory.objects.all()
#
#         # for cat in content_categories:
#         #     contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
#         #     print(contents[cat.key])
#
#         # 渲染模板的上下文
#         # context = {
#         #     'contents': contents,
#         # }
#         # data = []
#         # contents = Content.objects.filter(category=1)
#         # for i in contents:
#         #     item = {}
#         #     item['image'] = str(i.image)
#         #     item['title'] = i.title
#         #     data.append(item)
#         # print(data)
#         # return JsonResponse({'context': data})
#         # return render(request, 'index.html', context)
#
#         # return JsonResponse({'code':200,'categories':categories})

class IndexView(View):
    """首页广告"""

    def get(self, request):
        """提供首页广告界面"""
        # 查询商品频道和分类
        categories = get_categories()

        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        skus = SKU.objects.filter(stock__gt=0).order_by('-create_time')[:18]
        sku_list = []
        for sku in skus:
            sku_list.append({
                'name': sku.name,
                'price': sku.price,
                'default_image_url': str(sku.default_image),
                'id': sku.id,
            })
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
        index_lbt = []
        for i in contents['index_lbt']:
            item = {}
            item['title'] = i.title
            item['url'] = i.url
            item['image'] = str(i.image)
            item['text'] = i.text
            item['sequence'] = i.sequence
            item['status'] = i.status
            index_lbt.append(item)
        return JsonResponse({'index_lbt': index_lbt,
                             'categories': categories,
                             'sku': sku_list})


class ListView(View):

    def get(self, request, category_id):
        # 1.接收参数
        # 排序字段
        ordering = request.GET.get('ordering')
        # 每页多少条数据
        page_size = request.GET.get('page_size')
        # 要第几页数据
        page = request.GET.get('page')
        # 2.获取分类id
        # 3.根据分类id进行分类数据的查询验证
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 4.获取面包屑数据
        breadcrumb = get_breadcrumb(category)

        # 5.查询分类对应的sku数据，然后排序，然后分页
        skus = SKU.objects.filter(category=category, is_launched=True, stock__gt=0).order_by(ordering)
        # 分页
        from django.core.paginator import Paginator
        # object_list, per_page
        # object_list   列表数据
        # per_page      每页多少条数据
        paginator = Paginator(skus, per_page=page_size)

        # 获取指定页码的数据
        page_skus = paginator.page(page)

        sku_list = []
        # 将对象转换为字典数据
        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })

        # 获取总页码
        total_num = paginator.num_pages

        # 6.返回响应
        return JsonResponse(
            {'code': 0, 'errmsg': 'ok', 'list': sku_list, 'count': total_num, 'breadcrumb': breadcrumb})


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行JSON数据"""
        # 根据销量倒序
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        # 序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_skus})

class MysearchView(View):
    """搜索商品"""

    def get(self, request):
        q = request.GET.get("q")
        # print(q)
        skus = SKU.objects.filter(name__icontains=q)
        sku = []
        for i in skus:
            sku.append({
                'name': i.name,
                'price': i.price,
                'default_image_url': str(i.default_image),
                'id': i.id,
                # 'name':sku.name,
            })
        return JsonResponse({'code': 200, 'sku': sku})


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.filter(id=sku_id).first()
            item = {}
            item['name'] = sku.name
            item['caption'] = sku.caption
            item['price'] = sku.price
            item['market_price'] = sku.market_price
            item['default_image'] = str(sku.default_image)
            item['desc_detail'] = sku.spu.desc_detail

        except SKU.DoesNotExist:
            # return render(request, '404.html')
            return JsonResponse('error')

        # 查询商品频道分类
        # categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')

        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            #  -sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # print(goods_specs.id)
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options
        goods_specs_list = []
        names = []
        for i in goods_specs:
            # print(i.name)
            for j in i.spec_options:
                # print(j.value)
                goods_specs_list.append({
                    'name': i.name,
                    'shuxing': j.value,
                    'sku_id': j.sku_id,

                })
        # 渲染页面
        # print(goods_specs_list)
        context = {
            # 'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': item,
            'goods_specs': goods_specs_list
        }
        # print(context.get('sku'))
        return JsonResponse(context)


class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        try:
            # 1.获取当前商品
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 2.查询日期数据
        from datetime import date
        # 获取当天日期
        today_date = date.today()

        from apps.goods.models import GoodsVisitCount
        try:
            # 3.如果有当天商品分类的数据  就累加数量
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except:
            # 4. 没有, 就新建之后在增加
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '新增失败'})

        return JsonResponse({'code': 0, 'errmsg': 'OK'})
